<template>
  <div class="app-container">
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <div class="filter-container">
        <el-input
          v-model="listQuery.testTitle"
          placeholder="测试标题"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter="handleFilter"
        />
        <el-select
          v-model="listQuery.level"
          placeholder="评估等级"
          clearable
          style="width: 200px"
          class="filter-item"
        >
          <el-option label="正常" value="正常" />
          <el-option label="轻度抑郁" value="轻度抑郁" />
          <el-option label="中度抑郁" value="中度抑郁" />
          <el-option label="重度抑郁" value="重度抑郁" />
        </el-select>
        <el-button class="filter-item" type="primary" size="default" @click="handleFilter">
          搜索
        </el-button>
        <el-button class="filter-item" size="default" @click="resetQuery">
          重置
        </el-button>
      </div>

      <!-- 测试记录列表 -->
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="加载中..."
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column label="测试标题" align="center">
          <template #default="scope">
            {{ scope.row.testTitle || '未知测试' }}
          </template>
        </el-table-column>
        <el-table-column label="总分" prop="totalScore" align="center" />
        <el-table-column label="评估等级" align="center">
          <template #default="scope">
            <el-tag :type="getLevelTagType(scope.row.level)">{{ scope.row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="分析建议" align="center">
          <template #default="scope">
            <el-tooltip :content="scope.row.analysis" placement="top">
              <span>{{ scope.row.analysis?.slice(0, 20) }}{{ scope.row.analysis?.length > 20 ? '...' : '' }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="评审状态" align="center">
          <template #default="scope">
            <el-tooltip v-if="scope.row.reviewedBy" :content="`评审人: ${scope.row.reviewerName || '未知'}\n评审时间: ${formatTime(scope.row.reviewTime)}\n评审意见: ${scope.row.reviewComments || '无'}`" placement="top">
              <el-tag type="success">已评审</el-tag>
            </el-tooltip>
            <el-tag v-else type="info">未评审</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="viewResult(scope.row.recordId)"
            >
              查看结果
            </el-button>
            <el-button
              v-if="!scope.row.reviewedBy"
              type="success"
              size="small"
              @click="reviewTest(scope.row)"
            >
              评审
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-show="total > 0"
        :current-page="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

      <!-- 评审对话框 -->
      <el-dialog
        title="测试评审"
        v-model="reviewDialogVisible"
        width="50%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <div v-if="currentRecord" class="review-dialog-content">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="测试标题">
              {{ currentRecord.testTitle }}
            </el-descriptions-item>
            <el-descriptions-item label="总分">
              {{ currentRecord.totalScore }}
            </el-descriptions-item>
            <el-descriptions-item label="评估等级">
              {{ currentRecord.level }}
            </el-descriptions-item>
            <el-descriptions-item label="分析结果">
              {{ currentRecord.analysis }}
            </el-descriptions-item>
            <el-descriptions-item label="建议">
              {{ currentRecord.suggestions }}
            </el-descriptions-item>
          </el-descriptions>

          <el-form :model="reviewForm" label-width="100px" class="review-form">
            <el-form-item label="评审意见" required>
              <el-input
                v-model="reviewForm.reviewComments"
                type="textarea"
                :rows="4"
                placeholder="请输入评审意见"
              />
            </el-form-item>
          </el-form>
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="reviewDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitReview">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { getTestRecordList, reviewTestRecord } from '../../api/psychological-test'
import { getUserInfo } from '../../api/user'
import { formatTime } from '../../utils/format'

export default {
  name: 'TestRecordList',
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        testTitle: '',
        level: ''
      },
      reviewDialogVisible: false,
      reviewForm: {
        reviewComments: ''
      },
      currentRecord: null,
      currentUser: null
    }
  },
  async created() {
    try {
      const response = await getUserInfo()
      if (response.code === 200) {
        this.currentUser = response.data
        this.getList()
      } else {
        this.$message.error('获取用户信息失败，请重新登录')
        this.$router.push('/login')
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      this.$message.error('获取用户信息失败，请重新登录')
      this.$router.push('/login')
    }
  },
  methods: {
    async getList() {
      this.listLoading = true
      try {
        const response = await getTestRecordList({
          pageNum: this.listQuery.pageNum,
          pageSize: this.listQuery.pageSize,
          testTitle: this.listQuery.testTitle,
          level: this.listQuery.level,
          role: this.currentUser?.role
        })
        if (response.code === 200) {
          this.list = response.data.records.map(record => ({
            ...record,
            reviewedBy: record.reviewedBy || null,
            reviewerName: record.reviewerName || null,
            reviewTime: record.reviewTime || null,
            reviewComments: record.reviewComments || null
          }))
          this.total = response.data.total
        } else {
          this.$message.error(response.msg || '获取列表失败')
        }
      } catch (error) {
        console.error('获取测试记录列表失败:', error)
        this.$message.error('获取列表失败，请重试')
      } finally {
        this.listLoading = false
      }
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val
      this.getList()
    },
    formatTime,
    viewResult(id) {
      this.$router.push({
        path: `/test/result/${id}`,
        query: { from: 'test-record-list' }
      })
    },
    reviewTest(record) {
      console.log('Review button clicked:', record)
      this.currentRecord = record
      this.reviewForm.reviewComments = ''
      this.reviewDialogVisible = true
      console.log('Dialog visibility:', this.reviewDialogVisible)
      console.log('Current record:', this.currentRecord)
    },
    async submitReview() {
      if (!this.reviewForm.reviewComments) {
        this.$message.warning('请输入评审意见')
        return
      }

      if (!this.currentUser || !this.currentUser.id) {
        this.$message.error('获取用户信息失败，请重新登录')
        this.$router.push('/login')
        return
      }

      try {
        const response = await reviewTestRecord(this.currentRecord.id, {
          reviewedBy: this.currentUser.id,
          reviewComments: this.reviewForm.reviewComments
        })
        
        if (response.code === 200) {
          this.$message.success('评审成功')
          this.reviewDialogVisible = false
          this.reviewForm.reviewComments = ''
          this.currentRecord = null
          await this.getList()
        } else {
          throw new Error(response.msg || '评审失败')
        }
      } catch (error) {
        console.error('评审失败:', error)
        this.$message.error(error.message || '评审失败，请重试')
      }
    },
    resetQuery() {
      this.listQuery = {
        pageNum: 1,
        pageSize: 10,
        testTitle: '',
        level: ''
      }
      this.getList()
    },
    getLevelTagType(level) {
      const types = {
        '正常': '',
        '轻度抑郁': 'warning',
        '中度抑郁': 'danger',
        '重度抑郁': 'danger'
      }
      return types[level] || 'info'
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.box-card {
  margin-bottom: 20px;
}
.filter-container {
  padding-bottom: 10px;
}
.filter-item {
  margin-right: 10px;
}
.review-dialog-content {
  padding: 20px 0;
}
.review-form {
  margin-top: 20px;
}
</style> 